package com.gxuwz.bignews.view.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.gxuwz.bignews.R;
import com.bumptech.glide.Glide;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.gxuwz.bignews.model.db.NewsFavoriteDao;
import com.gxuwz.bignews.model.entity.NewsFavorite;

public class NewsDetailActivity extends AppCompatActivity {

    private static final String API_KEY = "cb4e16f1adcff115fc792a51c6261c20";
    //284c099e2102d09a9e7f237ea46fbdc4
    //cb4e16f1adcff115fc792a51c6261c20
    // API KEY
    private TextView tvTitle, tvSource, tvDate, tvCategory;
    private ImageView ivNewsImage;
    private WebView webViewContent;
    private ImageButton btnBack, btnFavorite, btnShare;
    private String uniqueKey;
    
    // 用于分享的新闻数据
    private String newsTitle = "";
    private String newsUrl = "";
    private String newsContent = "";

    // 关注相关字段
    private boolean isFavorite = false;
    private String phone = "";
    private String title = "";
    private String thumbnailPic = "";
    private String url = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        
        // 初始化视图
        initViews();
        
        // 获取新闻唯一ID
        uniqueKey = getIntent().getStringExtra("uniquekey");
        
        if (uniqueKey != null && !uniqueKey.isEmpty()) {
            // 获取新闻详情
            fetchNewsDetail(uniqueKey);
        } else {
            Log.e("NewsDetail", "No uniquekey provided");
            finish();
        }
    }
    
    private void initViews() {
        tvTitle = findViewById(R.id.tv_news_title);
        tvSource = findViewById(R.id.tv_news_source);
        tvDate = findViewById(R.id.tv_news_date);
        tvCategory = findViewById(R.id.tv_news_category);
        ivNewsImage = findViewById(R.id.iv_news_image);
        webViewContent = findViewById(R.id.webview_content);
        
        // 初始化按钮
        btnBack = findViewById(R.id.btn_back);
        btnFavorite = findViewById(R.id.btn_favorite);
        btnShare = findViewById(R.id.btn_share);
        
        // 设置返回按钮
        btnBack.setOnClickListener(v -> finish());
        
        // 设置关注按钮点击事件
        btnFavorite.setOnClickListener(v -> {
            if (phone == null || phone.isEmpty() || uniqueKey == null || uniqueKey.isEmpty()) {
                Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            NewsFavoriteDao dao = new NewsFavoriteDao(this);
            if (isFavorite) {
                dao.deleteFavorite(phone, uniqueKey);
                isFavorite = false;
                btnFavorite.setImageResource(android.R.drawable.btn_star);
                Toast.makeText(this, "已取消关注", Toast.LENGTH_SHORT).show();
            } else {
                NewsFavorite favorite = new NewsFavorite(phone, uniqueKey, title, thumbnailPic, url, System.currentTimeMillis());
                dao.insertFavorite(favorite);
                isFavorite = true;
                btnFavorite.setImageResource(android.R.drawable.btn_star_big_on);
                Toast.makeText(this, "已关注", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 设置分享按钮点击事件
        btnShare.setOnClickListener(v -> {
            copyShareLinkToClipboard();
        });
    }
    
    /**
     * 复制分享链接到剪贴板
     */
    private void copyShareLinkToClipboard() {
        if (newsUrl != null && !newsUrl.isEmpty()) {
            // 获取剪贴板管理器
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            
            // 创建新的剪贴数据
            ClipData clip = ClipData.newPlainText("新闻链接", newsUrl);
            
            // 设置剪贴板内容
            clipboard.setPrimaryClip(clip);
            
            // 显示提示
            Toast.makeText(this, "已复制分享链接至剪贴板", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "分享链接不可用", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void fetchNewsDetail(String uniquekey) {
        new Thread(() -> {
            try {
                String apiUrl = "https://v.juhe.cn/toutiao/content?key=" + API_KEY + "&uniquekey=" + uniquekey;
                URL url = new URL(apiUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                int code = conn.getResponseCode();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    reader.close();
                    parseNewsDetail(sb.toString());
                }
            } catch (Exception e) {
                Log.e("NewsDetailApi", "error", e);
                new Handler(Looper.getMainLooper()).post(() -> {
                    Log.e("NewsDetailApi", "Failed to fetch news detail");
                });
            }
        }).start();
    }
    
    private void parseNewsDetail(String json) {
        try {
            JSONObject obj = new JSONObject(json);
            if (obj.getInt("error_code") == 0) {
                JSONObject result = obj.getJSONObject("result");
                JSONObject detail = result.getJSONObject("detail");
                String content = result.getString("content");
                
                title = detail.optString("title", "");
                String date = detail.optString("date", "");
                String category = detail.optString("category", "");
                String authorName = detail.optString("author_name", "");
                thumbnailPic = detail.optString("thumbnail_pic_s", "");
                url = detail.optString("url", "");
                
                // 保存数据用于分享
                newsTitle = title;
                newsUrl = url;
                newsContent = content;

                // 写入历史记录
                try {
                    android.content.SharedPreferences sp = getSharedPreferences("user_info", Context.MODE_PRIVATE);
                    phone = sp.getString("phone", "");
                    if (phone != null && !phone.isEmpty()) {
                        com.gxuwz.bignews.model.entity.NewsHistory history = new com.gxuwz.bignews.model.entity.NewsHistory(
                            phone, uniqueKey, title, thumbnailPic, url, System.currentTimeMillis()
                        );
                        new com.gxuwz.bignews.model.db.NewsHistoryDao(this).insertOrUpdateHistory(history);
                    }
                } catch (Exception e) {
                    android.util.Log.e("HistoryWrite", "写入历史失败", e);
                }

                // 检查是否已关注，切换按钮UI
                new Handler(Looper.getMainLooper()).post(() -> {
                    NewsFavoriteDao dao = new NewsFavoriteDao(this);
                    isFavorite = (phone != null && !phone.isEmpty() && dao.isFavorite(phone, uniqueKey));
                    btnFavorite.setImageResource(isFavorite ? android.R.drawable.btn_star_big_on : android.R.drawable.btn_star);
                    // 设置基本信息
                    tvTitle.setText(title);
                    tvSource.setText(authorName);
                    tvDate.setText(date);
                    tvCategory.setText(category);
                    
                    // 设置图片
                    if (thumbnailPic != null && !thumbnailPic.isEmpty()) {
                        ivNewsImage.setVisibility(View.VISIBLE);
                        Glide.with(this)
                                .load(thumbnailPic)
                                .into(ivNewsImage);
                    } else {
                        ivNewsImage.setVisibility(View.GONE);
                    }
                    
                    // 设置内容
                    setupWebViewContent(content);
                });
            } else {
                Log.e("NewsDetailParse", "API error: " + obj.getInt("error_code"));
            }
        } catch (JSONException e) {
            Log.e("NewsDetailParse", "JSON解析错误", e);
        }
    }
    
    private void setupWebViewContent(String content) {
        // 构建HTML内容
        String htmlContent = "<html><head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" +
                "<style>" +
                "body { font-family: sans-serif; line-height: 1.5; padding: 8px; }" +
                "img { max-width: 100%; height: auto; }" +
                "p { margin-bottom: 16px; }" +
                "</style></head><body>" + content + "</body></html>";
                
        webViewContent.getSettings().setJavaScriptEnabled(false); // 安全起见，禁用JavaScript
        webViewContent.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null);
    }
} 